﻿var name = $("#name"),
			email = $("#email"),
			password = $("#password"),
            salegrp = $("#msalegrp"),
			allFields = $([]).add(name).add(email).add(password).add(salegrp),
			tips = $(".validateTips");
var AllRoleDB;
var helper = new Helper();
var grid;
var gridRole;
var data = [];
var columns = [
    { id: "UserName", name: "UserName", field: "UserName", width: 120, cssClass: "cell-title" },
    { id: "DomainName", name: "DomainName", field: "DomainName" },
    { id: "FirstName", name: "FirstName", field: "FirstName", width: 80, resizable: false },
    { id: "Lastname", name: "Lastname", field: "Lastname", minWidth: 60 },
    { id: "Email", name: "Email", field: "Email", minWidth: 60 },
    { id: "Tel", name: "Tel", field: "Tel", minWidth: 60, editor: Slick.Editors.LongText },
    { id: "Fax", name: "Fax", field: "Fax", minWidth: 60, editor: Slick.Editors.LongText },
    { id: "msalegrp", name: "Sale Group", field: "msalegrp", minWidth: 60, editor: Slick.Editors.Text, validator: checkLengthSaleGrp },
    { id: "RoleName", name: "RoleName", field: "RoleName", sortable: false, width: 80, minWidth: 20, maxWidth: 80, cssClass: "cell-effort-driven", editor: Slick.Editors.RoleSelect },
    { id: "License", name: "License", field: "ImageLicenseRelative", sortable: false, width: 80, minWidth: 20, maxWidth: 80, formatter: Slick.Formatters.Image },
    { id: "IsDisable", name: "IsDisable", field: "IsDisable", minWidth: 60, formatter: Slick.Formatters.Checkmark, editor: Slick.Editors.Checkbox },
    { id: "CreateDate", name: "CreateDate", field: "CreateDate", formatter: function (row, cell, value, columnDef,
dataContext) {
        if (value == null) {
            return '';
        }
        if (value != '0000-00-00') {
            if (value.indexOf('/Date') == 0) {
                var kkk = new Date(parseInt(value.replace(/\/+Date\(([\d+-]+)\)\/+/, '$1')));
                return $.datepicker.formatDate('mm/dd/yy', kkk);
            }
            else {

                return value;
            }

        } else {
            return '';
        }
    }, minWidth: 60
    },
    { id: "ModifyDate", name: "ModifyDate", field: "ModifyDate", formatter: function (row, cell, value, columnDef,
dataContext) {
        if (value == null) {
            return '';
        }
        if (value != '0000-00-00') {
            if (value.indexOf('/Date') == 0) {
                var kkk = new Date(parseInt(value.replace(/\/+Date\(([\d+-]+)\)\/+/, '$1')));
                return $.datepicker.formatDate('mm/dd/yy', kkk);
            }
            else {
                return value;
            }
        } else {
            return '';
        }
    }, minWidth: 60
    }
  ];
var rolecolumns = [
    { id: "RoleID", name: "RoleID", field: "RoleID" },
    { id: "RoleName", name: "RoleName", field: "RoleName" },
    { id: "RoleDescription", name: "RoleDescription", field: "RoleDescription", width: 100, editor: Slick.Editors.LongText },
    { id: "IsDisable", name: "IsDisable", field: "IsDisable", minWidth: 60, formatter: Slick.Formatters.Checkmark, editor: Slick.Editors.Checkbox },
    { id: "CreateDate", name: "CreateDate", field: "CreateDate", formatter: function (row, cell, value, columnDef,
dataContext) {
        if (value == null) {
            return '';
        }
        if (value != '0000-00-00') {
            if (value.indexOf('/Date') == 0) {
                var kkk = new Date(parseInt(value.replace(/\/+Date\(([\d+-]+)\)\/+/, '$1')));
                return $.datepicker.formatDate('mm/dd/yy', kkk);
            }
            else {
                return value;
            }
            //alert(kkk);

        } else {
            return '';
        }
    }, minWidth: 60
    }
  ];
var checkboxSelector = new Slick.CheckboxSelectColumn({
    cssClass: "slick-cell-checkboxsel"
});
var checkboxSelectorRole = new Slick.CheckboxSelectColumn({
    cssClass: "slick-cell-checkboxsel"
});
columns.splice(0, 0, checkboxSelector.getColumnDefinition());
rolecolumns.splice(0, 0, checkboxSelectorRole.getColumnDefinition());
var options = {
    editable: true,
    enableRowReordering: true,
    enableCellNavigation: true,
    asyncEditorLoading: false,
    autoEdit: false
};
var optionsRole = {
    editable: true,
    enableRowReordering: true,
    enableCellNavigation: true,
    asyncEditorLoading: false,
    autoEdit: false
};
var users = null;
function RefreshUser(parameters) {
    helper.GetUserDb(function (userdb) {
        users = userdb.RMember;
        grid = new Slick.Grid("#UserManagerGrid", userdb.RMember, columns, options);
        grid.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: true }));
        grid.registerPlugin(checkboxSelector);
        grid.onCellChange.subscribe(function (e, args) {
            updateUser(args.item);
        });
    });
}
function RefreshRole(parameters) {
    helper.GetRoleDb(function (roledb) {
        gridRole = new Slick.Grid("#UserRoleGrid", roledb, rolecolumns, optionsRole);
        gridRole.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: true }));
        gridRole.registerPlugin(checkboxSelectorRole);
        gridRole.onCellChange.subscribe(function (e, args) {
            updateRole(args.item);
        });
    });

}

function updateTips(t) {
    tips
				.text(t)
				.addClass("ui-state-highlight");
    setTimeout(function () {
        tips.removeClass("ui-state-highlight", 1500);
    }, 500);
}

function checkLength(o, n, min, max) {
    if (o.val().length > max || o.val().length < min) {
        o.addClass("ui-state-error");
        updateTips("Length of " + n + " must be between " +
					min + " and " + max + ".");
        return false;
    } else {
        return true;
    }
}

function checkLengthSaleGrp(value, o) {

    if (o == "sale" || o == "Sale") {
        if (value.length > 3 || value.length <= 0) {
            MsgBox("Length of Sale Group must be between " +
                0 + " and " + 3 + ".");
            updateTips("Length of Sale Group must be between " +
                0 + " and " + 3 + ".");
            $("#msalegrp").addClass("ui-state-error");
            return {
                valid: false,
                msg: "Length of Sale Group must be between " +
                0 + " and " + 3 + "."
            };
        } else {
            var salegrp = value;
            var exitsSalegrp = jQuery.grep(users, function(element, index) {
                return element.msalegrp.toLowerCase() == salegrp.toLowerCase();
            });
            if (exitsSalegrp.length > 0) {
                MsgBox('Sale Group ' + salegrp + ' already exits in database');
                updateTips('Sale Group ' + salegrp + ' already exits in database');
                $("#msalegrp").addClass("ui-state-error");
                return { valid: false, msg: 'Sale Group ' + salegrp + ' already exits in database' };
            } else {
                MsgBox('');
                updateTips('');
                $("#msalegrp").removeClass("ui-state-error");
                return { valid: true, msg: null };
            }
        }
    }
    else {
        return { valid: true, msg: null };
    }
}

function checkRegexp(o, regexp, n) {
    if (!(regexp.test(o.val()))) {
        o.addClass("ui-state-error");
        updateTips(n);
        return false;
    } else {
        return true;
    }
}

function deleteUser(userName,func) {

    helper.DeleteUserDb(userName, function (data) {
        RefreshUser();
        MsgBox('Delete ' + data + ' rows success');
    });
}

function deleteRole(role) {

    helper.DeleteRoleDb(role, function (data) {
        RefreshRole();
        MsgBox('Delete ' + data + ' rows success');
    });
}
function updateRole(RoleData) {
    helper.UpdateRoleDb(RoleData, function (data) {
        MsgBox('Update ' + data + ' rows success');
    });
}

function updateUser(UserData) {
    
    
        helper.UpdateUserDb(UserData, function (data) {
            MsgBox('Update ' + data + ' rows success');
        });
    
    
}
function FormRoleClear() {
    $('#rolenametxt').val('');
    $('#roleDescripttxt').val('');
}
function FormUserClear() {
    $('#name').val('');
    $('#email').val('');
    $('#password').val('');
    $('#msalegrp').val('');
}

function showImage(src) {

    window.open('/Page/ImageUpload.aspx?u=' + src, 'window', 'width=500,height=320,resizable,scrollbars,toolbar,menubar'); return false;
}
function bindRoleDropdown(parameters) {
    $("#SelectRole >option").remove('');
    helper.GetRoleDb(function (data) {
        $.each(data, function (key, value) {
            if (value.IsDisable != true) {
                $("#SelectRole").append($("<option></option>").val(value.RoleName).html(value.RoleName));
            }
        });

    });
}

